package com.kun.video.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.kun.video.AbstractApplication;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Window;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;

/**
 * TODO
 *
 * @author gzc
 * @since 2025/3/1
 **/
public class ChooserUtil {
    private static final Logger log = LoggerFactory.getLogger(ChooserUtil.class);
    // 缓存最近有效的初始目录
    private static final AtomicReference<File> LAST_VALID_DIR = new AtomicReference<>();
    // Window与FileChooser实例映射（避免多窗口重复创建）
    private static final ConcurrentHashMap<Window, FileChooser> FILE_CHOOSER_CACHE = new ConcurrentHashMap<>();
    private static final ConcurrentHashMap<Window, DirectoryChooser> DIR_CHOOSER_CACHE = new ConcurrentHashMap<>();

    // 预定义常用文件过滤器（避免重复创建）
    public static final FileChooser.ExtensionFilter IMAGE_FILTER =
            new FileChooser.ExtensionFilter("Images", "*.png", "*.jpg", "*.jpeg", "*.webp");
    public static final FileChooser.ExtensionFilter TEXT_FILTER =
            new FileChooser.ExtensionFilter("Text Files", "*.txt");
    public static final FileChooser.ExtensionFilter ALL_FILES_FILTER =
            new FileChooser.ExtensionFilter("All Files", "*.*");

    public enum FileFormat {
        /**
         * 图片
         */
        IMAGE("Images", "*.png", "*.jpg", "*.jpeg", "*.webp"),
        VIDEO("Video", "*.mp4", "*.mkv"),
        TXT("Text Files", "*.txt"),
        ALL("All Files", "*.*"),
        ;

        private final String desc;
        private final String[] fileFormatName;

        FileFormat(String desc, String... fileFormatName) {
            this.desc = desc;
            this.fileFormatName = fileFormatName;
        }

        public FileChooser.ExtensionFilter getFilter() {
            return new FileChooser.ExtensionFilter(desc, fileFormatName);
        }

        public String getDesc() {
            return desc;
        }

        public String[] getFileFormatName() {
            return fileFormatName;
        }
    }

    private final static FileChooser FILE_CHOOSER = new FileChooser();

    public static File showFile(FileFormat fileFormat) {
        return showFile("", "", null, fileFormat);
    }

    public static File showFile(String title, FileFormat fileFormat) {
        return showFile(title, "", null, fileFormat);
    }

    public static File showFile(String title, String initialDirPath, Window owner, FileFormat fileFormat) {
        if (fileFormat == null) {
            fileFormat = FileFormat.ALL;
        }
        if (owner == null) {
            owner = AbstractApplication.getAppStage();
        }
        if (StrUtil.isBlank(title)) {
            title = "选择文件";
        }

        FILE_CHOOSER.setTitle(title);
        // 添加过滤器（避免重复创建）
        if (ArrayUtil.isNotEmpty(fileFormat.getFileFormatName())) {
            FILE_CHOOSER.setSelectedExtensionFilter(fileFormat.getFilter());
        }
        File initialDirectory = resolveInitialDirectory(initialDirPath);
        if (initialDirectory != null) {
            FILE_CHOOSER.setInitialDirectory(initialDirectory);
        }
        Window finalOwner = owner;
        ComUtil.uiThreadRun(() -> {
            LAST_VALID_DIR.set(FILE_CHOOSER.showOpenDialog(finalOwner));
        });
        File selectedFile = LAST_VALID_DIR.get();
        updateLastValidDir(selectedFile);
        log.info("选择文件 -> {}", selectedFile != null ? selectedFile.getAbsolutePath() : "");
        return selectedFile;
    }

    public static List<File> showMultiFile(String title, FileFormat fileFormat) {
        return showMultiFile(title, "", null, fileFormat);
    }

    public static List<File> showMultiFile(String title, String initialDirPath, Window owner, FileFormat fileFormat) {
        if (fileFormat == null) {
            fileFormat = FileFormat.ALL;
        }
        if (owner == null) {
            owner = AbstractApplication.getAppStage();
        }
        if (StrUtil.isBlank(title)) {
            title = "选择多个文件";
        }

        FILE_CHOOSER.setTitle(title);
        // 添加过滤器（避免重复创建）
        if (ArrayUtil.isNotEmpty(fileFormat.getFileFormatName())) {
            FILE_CHOOSER.setSelectedExtensionFilter(fileFormat.getFilter());
        }
        File initialDirectory = resolveInitialDirectory(initialDirPath);
        if (initialDirectory != null) {
            FILE_CHOOSER.setInitialDirectory(initialDirectory);
        }
        Window finalOwner = owner;
        AtomicReference<List<File>> fileList = new AtomicReference<>();
        ComUtil.uiThreadRun(() -> {
            fileList.set(FILE_CHOOSER.showOpenMultipleDialog(finalOwner));
            if (CollUtil.isNotEmpty(fileList.get())) {
                LAST_VALID_DIR.set(fileList.get().get(0));
            }
        });
        File selectedFile = LAST_VALID_DIR.get();
        updateLastValidDir(selectedFile);
        return fileList.get();
    }

    /**
     * 打开文件对话框（优化版）
     */
    public static File showOpenDialog(Window owner, String title,
                                      String initialDirPath,
                                      FileChooser.ExtensionFilter... filters) {
        FileChooser fc = getOrCreateFileChooser(owner);
        configureFileChooser(fc, title, initialDirPath, filters);
        File result = fc.showOpenDialog(owner);
        updateLastValidDir(result);
        return result;
    }

    /**
     * 保存文件对话框（优化版）
     */
    public static File showSaveDialog(Window owner, String title,
                                      String initialDirPath,
                                      FileChooser.ExtensionFilter... filters) {
        FileChooser fc = getOrCreateFileChooser(owner);
        configureFileChooser(fc, title, initialDirPath, filters);
        File result = fc.showSaveDialog(owner);
        updateLastValidDir(result);
        return result;
    }

    private final static DirectoryChooser DIRECTORY_CHOOSER = new DirectoryChooser();

    public static File showDir(String title) {
        return showDir(title, "", null);
    }

    public static File showDir(String title, String initialDirPath, Window owner) {
        configureDirectoryChooser(DIRECTORY_CHOOSER, title, initialDirPath);
        ComUtil.uiThreadRun(() -> {
            LAST_VALID_DIR.set(DIRECTORY_CHOOSER.showDialog(owner));
        });
        File selectedFile = LAST_VALID_DIR.get();
        updateLastValidDir(selectedFile);
        log.info("选择目录 -> {}", selectedFile != null ? selectedFile.getAbsolutePath() : "");
        return selectedFile;
    }

    /**
     * 选择目录对话框（优化版）
     */
    public static File showDirectoryDialog(Window owner, String title,
                                           String initialDirPath) {
        DirectoryChooser dc = getOrCreateDirectoryChooser(owner);
        configureDirectoryChooser(dc, title, initialDirPath);
        File result = dc.showDialog(owner);
        updateLastValidDir(result);
        return result;
    }

    // 从缓存获取或创建新的FileChooser
    private static FileChooser getOrCreateFileChooser(Window owner) {
        return FILE_CHOOSER_CACHE.computeIfAbsent(owner, k -> {
            FileChooser fc = new FileChooser();
            // 设置默认配置（根据需求调整）
            fc.setInitialDirectory(LAST_VALID_DIR.get());
            return fc;
        });
    }

    // 从缓存获取或创建新的DirectoryChooser
    private static DirectoryChooser getOrCreateDirectoryChooser(Window owner) {
        return DIR_CHOOSER_CACHE.computeIfAbsent(owner, k -> {
            DirectoryChooser dc = new DirectoryChooser();
            dc.setInitialDirectory(LAST_VALID_DIR.get());
            return dc;
        });
    }

    // 配置文件选择器（重置+配置）
    private static void configureFileChooser(FileChooser fc, String title,
                                             String initialDirPath,
                                             FileChooser.ExtensionFilter[] filters) {
        // 重置状态
        fc.getExtensionFilters().clear();
        fc.setTitle(title != null ? title : "Open");

        // 设置初始目录（优先级：参数 > 缓存 > 用户目录）
        File initialDir = resolveInitialDirectory(initialDirPath);
        if (initialDir != null) {
            fc.setInitialDirectory(initialDir);
        }

        // 添加过滤器（避免重复创建）
        if (filters != null) {
            for (var filter : filters) {
                fc.getExtensionFilters().add(filter);
            }
        }
    }

    // 配置目录选择器
    private static void configureDirectoryChooser(DirectoryChooser dc,
                                                  String title,
                                                  String initialDirPath) {
        dc.setTitle(title != null ? title : "Select Directory");
        File initialDir = resolveInitialDirectory(initialDirPath);
        if (initialDir != null) {
            dc.setInitialDirectory(initialDir);
        }
    }

    // 解析初始目录（带缓存验证）
    private static File resolveInitialDirectory(String path) {
        if (path == null || path.isEmpty()) {
            return LAST_VALID_DIR.get();
        }

        File dir = new File(path);
        if (dir.exists() && dir.isDirectory()) {
            LAST_VALID_DIR.set(dir);
            return dir;
        }
        return LAST_VALID_DIR.get();
    }

    // 更新最后有效目录
    private static void updateLastValidDir(File selectedFile) {
        if (selectedFile != null && selectedFile.exists()) {
            if (selectedFile.isFile()) {
                File parent = selectedFile.getParentFile();
                if (parent != null && parent.isDirectory()) {
                    LAST_VALID_DIR.set(parent);
                }
            } else {
                LAST_VALID_DIR.set(selectedFile);
            }
        }
    }

    // 清理缓存（建议在窗口关闭时调用）
    public static void cleanup(Window owner) {
        FILE_CHOOSER_CACHE.remove(owner);
        DIR_CHOOSER_CACHE.remove(owner);
    }

}
